package com.ttt.radioapp_core.activities;

import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import ar.com.tristeslos3tigres.rssfeedreader.RssFeedItem;
import ar.com.tristeslos3tigres.rssfeedreader.RssFeedReaderAsync;
import ar.com.tristeslos3tigres.rssfeedreader.feedsconfiguration.BlogspotConfiguration;
import ar.com.tristeslos3tigres.rssfeedreader.feedsconfiguration.FeedConfiguration;

import com.ttt.radioapp_core.R;
import com.ttt.radioapp_core.helpers.Intents;

public class ListadoNoticiasActivity extends Activity {
	public static final String URL_NEWS_FEED = "URL_NEWS_FEED";

	ListView list;
	List<RssFeedItem> data;
	String urlNewsFeed;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView();
		list = getListView();

		if (getIntent().hasExtra(URL_NEWS_FEED))
			urlNewsFeed = getIntent().getStringExtra(URL_NEWS_FEED);

		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				RssFeedItem noticia = (RssFeedItem) parent.getAdapter()
						.getItem(position);

				ListadoNoticiasActivity.this.startActivity(Intents.Noticias
						.getNoticiasIntent(ListadoNoticiasActivity.this,
								noticia));
			}
		});
		refreshList();
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.noticias, menu);
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		boolean result = false;
		if (item.getItemId() == R.id.action_refresh)
			refreshList();
		else
			result = super.onMenuItemSelected(featureId, item);

		return result;
	}


	protected void setContentView() {
		setContentView(R.layout.lista_noticias_activity);
	}

	protected ListView getListView() {
		return (ListView) findViewById(R.id.listView1);
	}

	private void refreshList() {
		try {
			FeedConfiguration config = new BlogspotConfiguration();
			new RssFeedReaderAsync(config, list).execute(new URL(urlNewsFeed));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
}